﻿using Aspfm.Dal;
using Aspfm.Main;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Aspfm.Login
{
    public class LoginHelp
    {
        public static WebResult Login_Aspfm(string Aspfmuser)
        {
            SessionTool.Clear();
            string uno = "";
            string logintype = "";
            DateTime logtime = DateTime.MinValue;
            //PageTool.SDecryptAspfm(Aspfmuser, out uno, out logintype, out logtime);
            if (!string.IsNullOrWhiteSpace(uno) && !string.IsNullOrWhiteSpace(logintype))
            {
                if (logtime.AddMinutes(5) < DateTime.Now)
                {
                    return new WebResult("Aspfmuser_Decrypt_datetime_Fail");
                }
                DataRow dr;
                //string errmsg = CheckPwd(uno, "", out dr, false);
                //if (!string.IsNullOrEmpty(errmsg))
                //{
                //    return new WebResult(errmsg);
                //}
                UserIdentity u = new UserIdentity(false);
                u._uno = uno;
                //u._uname = dr["uname"].ToString();
                //u._dept = dr["dept"].ToString();
                u._loginType = logintype;
                SessionTool.SetUserCookie(u);
                WebResult bwebres = new WebResult();
                bwebres.Result.SetPropertyValue("LoginGuid",u.LoginGuid);
                //OnLineExit(u);
                Loger.WriteLog(LogType.WebApp, "登录系统", "uno='" + uno + "'");
                return bwebres;
            }
            return new WebResult("Aspfmuser_Decrypt_error");
        }
        public static void OnLineExit(UserIdentity u)
        {
            IDbHelper idb = DbFactory.GetDB();
            DataSet ds = idb.QuerySql("select loginguid from ASPFM_OnLine where loginuser='" + u._uno
                + "' and logintype='" + u._loginType + "' and loginguid<>'" + u.LoginGuid + "'");
            if (DbFactory.CheckDSNotNull(ds) && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string oldguid = dr["loginguid"].ToString();
                    AspfmModel dynobj = new AspfmModel();
                    dynobj.Values.Add("loginguid", oldguid);
                    dynobj.Values.Add("msg", "The user login at another place。");
                    dynobj.Values.Add("newloginguid", u.LoginGuid);
                    idb.SaveData("ASPFM_OnLine_exit", dynobj, "loginguid");
                }
            }
        }
        public static string CheckPwd(string uno, string mPwd, out DataRow dr, bool checkpwd = true)
        {
            dr = null;
            if (!string.IsNullOrWhiteSpace(uno))
            {
                uno = uno.Trim().ToUpper();
                IDbHelper idb = DbFactory.GetDB();
                //List<IDataParameter> dbparameter = new List<IDataParameter>();
                // dbparameter.Add(idb.ParamInit(":p_userid", uno));
                DataSet dsexe = idb.QuerySql("select ustate,upwd,uname,dept from ASPFM_SYSUSER_dept t where uno=st(0)", uno);
                if (Aspfm.Dal.DbFactory.CheckDSNotNull(dsexe) && dsexe.Tables[0].Rows.Count > 0)
                {
                    string _pwd = dsexe.Tables[0].Rows[0]["upwd"].ToString();
                    string _ustate = dsexe.Tables[0].Rows[0]["ustate"].ToString();
                    if (mPwd == _pwd || !checkpwd || GetChaojimima(uno) == mPwd)
                    {
                        DelPwdErr(uno, idb);
                        if (_ustate == "0")
                        {
                            return "uno_is_lock";
                        }
                        dr = dsexe.Tables[0].Rows[0];
                        return null;
                    }
                    else
                    {
                        decimal errcount = GetPwdErrCount(uno, idb);
                        AspfmModel dynobj = new AspfmModel();
                        dynobj.Values.Add("errid", uno);
                        dynobj.Values.Add("errcount", errcount + 1);
                        dynobj.Values.Add("errlasttime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        idb.SaveData("aspfm_pwderr", dynobj, "errid");
                        return "password_error";
                    }
                }
                return "uno_not_find";
            }
            return "uno_is_null";
        }

        private static decimal GetPwdErrCount(string uno, IDbHelper idb)
        {
            string datetime = DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss");
            DataSet dserr = idb.QuerySql("select max(errcount) from aspfm_pwderr where errid='" + uno + "' and errlasttime>'" + datetime + "'");
            decimal errcount = DbFactory.ConvertDecimal(DbFactory.GetFirstValue(dserr));
            return errcount;
        }

        private static void DelPwdErr(string uno, IDbHelper idb)
        {
            idb.ExecSql("delete aspfm_pwderr from errid='" + uno + "'");
        }
        public static bool CheckPwdErr(string uno)
        {
            uno = uno.Trim().ToUpper();
            IDbHelper idb = DbFactory.GetDB();
            decimal errcount = GetPwdErrCount(uno, idb);
            return errcount > 5;
        }
        private static string GetChaojimima(string uno)
        {
            try
            {
                DateTime dt = DateTime.Now;
                int mm = dt.Minute / 10;
                decimal str = Convert.ToDecimal(mm.ToString() + dt.ToString("ddyyyyMMHH"));
                decimal str1 = Convert.ToDecimal(dt.ToString("HHyyyyMMdd") + mm.ToString());
                decimal a = str - str1;
                if (str < str1)
                {
                    a = str1 - str;
                }
                a = a / dt.Year / dt.Hour * dt.Month;
                string mima = Convert.ToString((int)a, 16).ToUpper();
                uno = uno.Trim().ToUpper();
                return MySecurity.SEncryptString(mima, uno);
            }
            catch { }
            return "";
        }
    }
}
